const cloud = require('wx-server-sdk')
cloud.init({env: 'your-env-id'})

exports.main = async (event, context) => {
  const db = cloud.database()
  const _ = db.command

  // 更新用户学习记录
  await db.collection('users').where({
    _openid: event.userInfo.openId
  }).update({
    data: {
      progress: _.inc(1),
      lastUpdate: db.serverDate(),
      [event.reportType]: _.inc(1)
    }
  })

  // 获取下一个单词逻辑
  const res = await db.collection('words')
    .aggregate()
    .match({ difficulty: event.reportType === 'mastered' ? _.neq('easy') : 'hard' })
    .sample({size:1})
    .end()

  return { nextWord: res.list[0] }
}